import { auth } from "@/api";
import { ERROR_TYPE } from "@/common/constants";
import { TokenUtils, UserInfoUtils } from "@/common/utils";
import store from "../index";

const state = {
  userInfo: UserInfoUtils.getUserInfo(),
  token: TokenUtils.getToken(),
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
    TokenUtils.setToken(token);
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo;
    UserInfoUtils.setUserInfo(userInfo);
  },
  CLEAR_USER_INFO: (state) => {
    state.userInfo = null;
    state.token = null;
    UserInfoUtils.removeUserInfo();
    TokenUtils.removeToken();
  },
};

const actions = {
  // 登录
  async login({ commit }, loginData) {
    try {
      const { data, success, msg } = await auth.login(loginData);
      if (success && data && data.token) {
        // 清除 professor 信息
        store.commit("professor/CLEAR_PROFESSOR_INFO");
        // 设置 token
        commit("SET_TOKEN", data.token);
        //过滤数据
        const userInfo = {
          id: data.userInfo.id,
          name: data.userInfo.name,
          phone: data.userInfo.phone,
        };
        commit("SET_USER_INFO", userInfo);
        return;
      }
      return Promise.reject({ 
        msg: msg || '登录失败，请检查输入信息', 
        type: ERROR_TYPE.BUSINESS 
      });
    } catch (error) {
      return Promise.reject(error);
    }
  },
  // 注销
  async logout({ commit }) {
    try {
      const { success, msg } = await auth.logout();
      if (success) {
        commit("CLEAR_USER_INFO");
        return;
      }
      return Promise.reject({ 
        msg: msg || '注销失败', 
        type: ERROR_TYPE.BUSINESS 
      });
    } catch (error) {
      return Promise.reject(error);
    }
  },
};

const user = {
  namespaced: true,
  state,
  mutations,
  actions,
};

export default user;
